"use strict"
import mode from '../../utils/mode.js'
import { getStore, setStore } from '../../utils/storage'
const App = getApp()
Page({
    onShareAppMessage () {   //分享好友
        // this.setData({
        //   isShare:1,
        // })
        return {
        title:this.data.shareText||'2AM官方小程序',
        path: `/pages/exclusive/exclusive?share_id=${this.data.userInfo&&this.data.userInfo.id?this.data.userInfo.id:'0'}&userName=${this.data.userInfo&&this.data.userInfo.user_nickname?this.data.userInfo.user_nickname:''}`,
        imageUrl: 'https://2am-project.cn/img/20220524/shareCard.png',   //分享图片
        }
    },
    data: {
        use_coupon:'',
        yugu_price:'',//预估价格
        shareText: '2AM官方小程序',  //分享内容
        night:false,
        showOut:false,
        showGood: false,
        goodsList: null,
        username: '',
        logo: App.globalData.logo,
        checked: false,
        selectAll: false,
        total_fee: '',
        totalPrice: 0,
        goodSpec: [
            {
                url: '../../image/icon/Group7561@2x.png',
                text: ['业内顶级超声波提取技术，更纯粹更高浓； 1%肌肽-配合姜黄铜，抑制自由基，保护胶原蛋白，内部抵御糖化。']
            },
            {
                url: '../../image/icon/Group7562@2x.png',
                text: ['天然植萃，加乘双抗', ' a.“超级抗氧果”诃子果提取物-促进胶原蛋白生成，抗氧抗糖双管齐下']
            },
        ],
        showMore: false,  //展示推荐商品
        isOpen: true,   //默认展开推荐商品
        pageFlag: false,
        isAdd: false,
        topClass: '',
        addCartList: [],
        goods: null, // 查看好物
        recommendGoods: [], //测试报告的推荐商品ID
        pageBackgroundColor: '#FFF'
    },
    onLoad: function (options) {
        if(options&&options.share_id){
            wx.setStorage({ key: "share_id", data: options.share_id })
            setStore('share_id', options.share_id)
        }
        this.setData({ isOpen: true })
    },
    onReady: function () { },
    onShow: function () {
        this.setTabbar()
        this.init()
    },
    handleClickDel(e){  //删除
        let { goodsList, addCartList } = this.data
        let that = this
        let item = e.currentTarget.dataset.index
        this.setData({
            setDelItem:item
        })
        wx.showModal({
            title: '提示',
            content: '确认删除此商品',
            showCancel: true,
            cancelText: '取消',
            cancelColor: '#AAAAAA',
            confirmText: '确定',
            confirmColor: '#000000',
            success: async (result) => {
                if (result.confirm) {
                    wx.showLoading({
                        title: '请求中',
                        mask: true,
                    })
                    let { code, data, msg } = await mode.recmoveGoods({
                        ids: item.id,
                        user_id: this.data.user_id
                    })
                    wx.hideLoading()
                    if (code == 1) {
                        wx.showToast({ title: '删除成功!' })
                        let list = [...goodsList, ...addCartList]
                        list.forEach((x, i) => {
                            if (x.id == item.id) {
                                list.splice(i, 1)
                            }
                        })
                        setStore('goodsList', list)
                        that.cartLists()
                    } else wx.showToast({ title: msg, icon: 'none' })
                } else {
                    console.log('点击取消');
                    // let lists = that.data.addCartList
                    // lists[index].number = 1
                    // that.setData({
                    //     addCartList:lists
                    // })
                }
            },
            fail: () => { },
            complete: () => { }
        })
    },
    setTabbar(){
        let night = this.hasNight(new Date().getHours())
        this.setData({
        night: night,
        })
        if (night) {
        wx.setTabBarStyle({
            color: '#AAA',
            selectedColor: '#fff',
            backgroundColor: '#000',
            borderStyle: "black",
        })
        wx.setTabBarItem({
            index: 0,
            selectedIconPath: "/image/navbar/1-1.png",
        }
        )
        wx.setTabBarItem({
            index: 1,
            selectedIconPath: "/image/navbar/2-1.png",
        })
        wx.setTabBarItem({
            index: 2,
            selectedIconPath: "/image/navbar/3-1.png",
        })
        wx.setTabBarItem({
            index: 3,
            selectedIconPath: "/image/navbar/4-1.png",
        })
        } else {
        wx.setTabBarStyle({
            color: '#AAA',
            selectedColor: '#000',
            backgroundColor: '#fff',
            borderStyle: "white",
        })
        wx.setTabBarItem({
            index: 0,
            selectedIconPath: "/image/navbar/1-3.png"
        }
        )
        wx.setTabBarItem({
            index: 1,
            selectedIconPath: "/image/navbar/2-3.png"
        })
        wx.setTabBarItem({
            index: 2,
            selectedIconPath: "/image/navbar/3-3.png"
        })
        wx.setTabBarItem({
            index: 3,
            selectedIconPath: "/image/navbar/4-3.png"
        })
        }
    },
    hasNight: function (hour) {
        return hour > 18 || hour < 7
    },
    async init () {
        var top = wx.getStorageSync('top')
        if (top != '' && top != undefined && top != null) {
            top = JSON.parse(top)
            this.setData({ code: top.num, })
        }
        if (typeof this.getTabBar === 'function' && this.getTabBar()) {
            this.getTabBar().setData({
                selected: 1
            })
        }
        var info = wx.getStorageSync('uinfo')
        if (info && info.user) {
            this.getUser(info.user.id)
            let n = info.user.user_nickname || ''
            let title =  n + '邀您开启精准护肤之旅'
            this.setData({
                shareText: title,
                userInfo: info.user,
                user_id: info.user.id || '',
                username: info.user.user_nickname || '',
                recommendGoods: info.user.goods_info_ids || []
            })
            wx.showShareMenu({
               menus: ['shareAppMessage']
            })
        } else {
            wx.hideShareMenu({
              menus: ['shareAppMessage', 'shareTimeline']
            })
            this.setData({ goodsList: [], topClass: 'color-e5' })
        }
        wx.hideLoading()
        setTimeout(() => {
            this.setData({
                pageFlag: true
            })
        }, 50)
        this.goodsThing() //查看好物  
    },
    onHide: function () {
        this.setData({
            showGood: false,
            pageBackgroundColor: '#FFF'
        })
        wx.setStorage({ key: 'isFrom', data: '/pages/exclusive/exclusive' })
        setStore('goodsList', [...this.data.goodsList, ...this.data.addCartList])
    },
    onUnload: function () { },
    onPullDownRefresh: function () { },
    onReachBottom: function () { },
    goReport(){
        //查看报告
        let { userInfo, user_id } = this.data
        if (!userInfo || userInfo.is_member != 1) {
            wx.setStorage({
                data: '/pages/questionnaire/questionnaire',
                key: 'lastUrl',
            })
            wx.navigateTo({
                url: '/pages/register/register',
            })
            return
        }
        mode.getReportList(user_id).then(
            item => {
                if (item && item.data.length > 0) {
                    let e = item.data[0]
                    wx.navigateTo({
                        url: '/pages/testReport/testRrport?id=' + e.id + '&answer=' + e.answer,
                    })
                }
            }
        )
    },
    async uploadNum(id,num){   //更新数量
        let { code, data,msg } = await mode.update_number({
            user_id: this.data.user_id,
            id: id,
            number: num
        })
        if(code!=1){
            wx.showToast({
              title: msg,
              icon:"none",
              duration:1000
            })
        }
    },
    async cartLists () {   //获取商品列表
        let that = this
        let { code, data } = await mode.cartLists({ user_id: this.data.user_id })
        if (code && data) {
            let hcList = wx.getStorageSync('goodsList')
            let uInfo = that.data.userInfo
            let addCartList = []
            let tuijian = []
            let cartGoodIds = this.data.recommendGoods
            data.forEach(v => {
                if(v.number>v.goods_can_sell_number&&v.goods_can_sell_number>0){
                    v.number = v.goods_can_sell_number
                    that.uploadNum(v.id,v.number)
                }
                hcList && Array.isArray(hcList) && hcList.forEach(x => {
                    if (v.id == x.id) {
                        v.selected = x.selected || false
                    }
                })
                if (uInfo && uInfo.consumption_discount && uInfo.consumption_discount < 10) {
                    if(uInfo.consumption_discount>0){
                        let oldP = v.retail_price * uInfo.consumption_discount / 10 * 1
                        v.vip_price = oldP.toFixed(2)
                    }else{
                        let oldP = v.retail_price*1
                        v.vip_price = oldP.toFixed(2)
                    }
                }
                // cartGoodIds.push(v.id - 0)
                v.isAdd = !cartGoodIds.includes(v.id + '')
                if (!v.isAdd && this.data.userInfo.is_over_test == 1) {
                    tuijian.push(v)
                } else {
                    addCartList.push(v)
                }
            })
            wx.setStorage({ key: 'cartGoodIds', data: cartGoodIds })
            let isAdd = !data.length ? false : data.every(x => x.isAdd)
            if (isAdd) {
                this.setData({ topClass: 'pt-40 color-e5 plr-30' })
            } else if (tuijian.length && !addCartList.length) {
                this.setData({ topClass: '' })
            } else if (tuijian.length && addCartList.length) {
                this.setData({ topClass: 'pt-4', })
            } else {
                this.setData({ topClass: 'color-e5' })
            }
            if (!addCartList.length) this.setData({ isOpen: true })
            this.setData({
                goodsList: tuijian || [],
                addCartList,
                isAdd
            })
            this.getTotalPrice()
        }
    },
    async update_number (e) {    //购物车数量变化
        let that = this
        let { goodsList, addCartList } = this.data
        let { index, id, list } = e.currentTarget.dataset
        if (e.detail == 0) {
            if (id && this.data.recommendGoods.includes(id + '')) {
                // let dataList = this.data[list]
                // dataList[index].number = 1
                // this.setData({ list: dataList })
                return
            }
            wx.showModal({
                title: '提示',
                content: '确认删除此商品',
                showCancel: true,
                cancelText: '取消',
                cancelColor: '#AAAAAA',
                confirmText: '确定',
                confirmColor: '#000000',
                success: async (result) => {
                    if (result.confirm) {
                        wx.showLoading({
                            title: '请求中',
                            mask: true,
                        })
                        let { code, data, msg } = await mode.recmoveGoods({
                            ids: id,
                            user_id: this.data.user_id
                        })
                        wx.hideLoading()
                        if (code == 1) {
                            wx.showToast({ title: '删除成功!' })
                            let list = [...goodsList, ...addCartList]
                            list.forEach((x, i) => {
                                if (x.id == id) {
                                    list.splice(i, 1)
                                }
                            })
                            setStore('goodsList', list)
                            that.cartLists()
                            // let arr = that.data.goodsList
                            // arr.splice(index, 1)
                            // that.setData({
                            //     goodsList: arr
                            // })
                            // this.getTotalPrice()
                        } else wx.showToast({ title: msg, icon: 'none' })

                    } else {
                        console.log('点击取消');
                        let lists = that.data.addCartList
                        lists[index].number = 1
                        that.setData({
                            addCartList:lists
                        })
                    }
                },
                fail: () => { },
                complete: () => { }
            })
            return
        }
        
        wx.showLoading({ mask: true })
        let { code, data } = await mode.update_number({
            user_id: this.data.user_id,
            id: e.target.dataset.id,
            number: e.detail
        })
        if (code == 1) {
            // goodsList[index].number = e.detail
            // this.setData({
            //     goodsList
            // })
            // if (goodsList[index].selected) {
            //     this.getTotalPrice()
            // }
            setStore('goodsList', [...this.data.goodsList, ...this.data.addCartList])
            this.cartLists()
        }
        setTimeout(() => {
            wx.hideLoading()
        }, 100)
    },
    toTest () {
        if (this.data.userInfo && this.data.userInfo.is_member == 1) {
            wx.navigateTo({
                url: '../questionnaire/questionnaire'
            })
        } else {
            wx.setStorage({
                data: '/pages/questionnaire/questionnaire',
                key: 'lastUrl',
            })
            wx.navigateTo({
                url: '/pages/register/register'
            })
        }

    },
    getUser (userid) {
        var that = this
        var uinfo = wx.getStorageSync('uinfo')
        // userid=100049
        // userid=545
        mode.getUserInfo(userid).then(item => {
            uinfo.user = item.data
            wx.setStorage({ key: 'uinfo', data: uinfo })
            let { report_no, proposal_text,user_nickname } = item.data
            
            let n= user_nickname || '好友'
            let title =  n + '邀您开启精准护肤之旅'
            this.setData({
                userInfo:item.data,
                shareText: title,
                user_id: item.data.id || '',
                username:  item.data.user_nickname || '',
                recommendGoods: item.data.goods_info_ids || []
            })
            setTimeout(async () => {
                await that.cartLists()
                that.checkAll()
            }, 50)
        })
    },
    goSettlement () {
        let { userInfo,use_coupon } = this.data
        let cartLists = [...this.data.goodsList, ...this.data.addCartList]
        let is_abroad = this.data.showOut?1:0
        if (!cartLists.some(x => x.selected)) {
            wx.showModal({
                title: '温馨提示',
                content: '请选择商品进行结算',
                showCancel: false
            })

        } else if (!userInfo || userInfo.is_member != 1) {
            wx.showModal({
                title: '系统提示',
                content: '请先注册为会员后再进行购买',
                success: (res) => {
                    if (res.confirm) {
                        wx.navigateTo({
                            url: '/pages/register/register'
                        })
                    }
                }
            })
            return
        } else {
            let arr = []
            cartLists.forEach(v => {
                if (v.selected) {
                    arr.push({
                        goods_id: v.id,
                        number: v.number
                    })
                }
            })
            wx.navigateTo({
                url: '/pages/settlement/settlement?is_cart=1&goods_info=' + JSON.stringify(arr)+'&isAbroad='+is_abroad+'&coupon_id='+use_coupon
            })
        }

    },
    goDetail (e) {
        let { goodid } = e.currentTarget.dataset
        // console.log(`%c>_> e=>`, 'color:#ff7b54;font-size:16px;', goodid, this.data.goods)
        if (goodid) {
            wx.navigateTo({
                url: '/pages/product-details/product-details?goodId=' + goodid
            })
        } else {
            wx.navigateTo({
                url: '/pages/product-details/product-details?goodId=' + this.data.goods.goods_id
            })
        }
    },

    onChangeAll () {
        // let arr = [...this.data.goodsList, ...this.data.addCartList]
        let { goodsList, addCartList } = this.data
        if (!goodsList.length && !addCartList.length) {
            wx.showToast({
                title: '选择商品为空！',
                icon: 'none'
            })
            return
        }
        let selectAll = !this.data.selectAll    // 是否全选状态
        let isOk = 0
        for (let i in goodsList) {
            let item = goodsList[i]
            if(item.goods_can_sell_number>0&&selectAll==true){
               item.selected = selectAll
               isOk = isOk+1
            }else{
                item.selected = false
            }
        }
        for (let i in addCartList) {
            let item = addCartList[i]
            if(item.goods_can_sell_number>0&&selectAll==true){
               item.selected = selectAll
               isOk = isOk+1
            }else{
                item.selected = false
            }
        }
        if(isOk<1&&selectAll==true){
            wx.showToast({
              title: '暂无可选产品',
              icon:'none'
            })
            selectAll = false
        } 
        this.setData({
            selectAll: selectAll,
            goodsList,
            addCartList
        })
        this.getTotalPrice()
    },
    onChange (event) {
        this.setData({
            checked: event.detail
        })
    },
    getTotalPrice () {  //获取总价
        let carts = [...this.data.goodsList, ...this.data.addCartList]
        let total = 0
        let arr = []
        for (let i = 0; i < carts.length; i++) {
            if (carts[i].selected) {
                let item ={
                    goods_id:carts[i].id,
                    number:carts[i].number
                }
                arr.push(item)
                total += parseFloat(carts[i].retail_price || 0) * carts[i].number
            }
        }
        let newP = total ? total.toFixed(2) : '000.00'
        if (this.data.userInfo && this.data.userInfo.consumption_discount>0) {
            newP = (total * this.data.userInfo.consumption_discount / 10 * 1)
            newP = parseFloat(newP).toFixed(2)
        }
        if(arr.length>0){
            wx.$api.estimatePrice({
                goods_info:JSON.stringify(arr),
                user_id:this.data.userInfo.id
            }).then(res=>{
                if(res.code){
                    let yg = res.data.sale_price*1
                    yg = yg.toFixed(2)
                    this.setData({
                        yugu_price:yg,
                        use_coupon:res.data.coupon_user_id
                    })
                }
            })
        }else{
            this.setData({
                yugu_price:'',
                use_coupon:''
            })
        }
        this.setData({
            totalPrice: newP
        })
    },
    selectList (e) {
        const { index, isadd } = e.currentTarget.dataset
        let { goodsList, addCartList } = this.data;
        (isadd ? addCartList : goodsList)[index].selected = !(isadd ? addCartList : goodsList)[index].selected
        this.setData({
            goodsList,
            addCartList
        })
        this.checkAll()
        this.getTotalPrice()
    },
    checkAll () {
        let carts = [...this.data.goodsList, ...this.data.addCartList]
        let result = carts.every(x => x.selected === true||x.goods_can_sell_number<1)
        let resultNum = carts.some(x => x.selected === true&&x.goods_can_sell_number>0)
        let isout = false 
        if (carts.length == 0){
            result = false
            isout = true
        }else{
            carts.forEach((x,i)=>{
                if(x.selected === true&&x.is_abroad === 1){
                    isout = true
                }
            })
        }
        if(!resultNum) result = false
        this.setData({
            selectAll: result,
            showOut:isout
        })
    },
    goLook () {  //查看好物
        let goods = this.data.goods
        if (goods.type==2) {   //多个产品
            let ids = goods.goods
            if(ids&&ids.length>0){
                wx.navigateTo({
                    url: '/pages/goodList/goodList?isGood=1' +'&menuName='+goods.page_name
                })
            }else{
                wx.showToast({
                  title: '暂无商品推荐',
                  icon:'none',
                  duration:1000
                })
            }
        } else if(goods.type==1) {
            setTimeout(() => {
                this.setData({
                    showGood: true,
                    pageBackgroundColor: '#000'
                })
            }, 300)
        }else if(goods.type==3) {
            wx.navigateTo({
                url: '/pages/activePage/activePage?name='+goods.title+'&url='+goods.img_content,
            })
        }else if(goods.type==4) {
            wx.navigateTo({
                url: '/pages/outLink/outLink?name='+goods.title+'&url='+goods.link_address,
            })
        }
    },
    showMore () {
        this.setData({
            showMore: !this.data.showMore,
            isOpen: !this.data.isOpen
        })
    },
    async goodsThing () {
        let { code, data } = await wx.$api.goodsThing()
        if (code == 1) {
            let { goodSpec } = this.data
            goodSpec[0].txt = data.content1
            goodSpec[1].txt = data.content2
            this.setData({ goods: data, goodSpec })
        }
    }
})